<?php
class Zing_Auth_Util
{
	const VERSION=1;
	const LONG_SESSION_TYPE=32;//bit 5
	const SHORT_SESSION_TYPE=0;
	const AUTHORIZED_SESSION=16;//bit 6
	const UNAUTHORIZED_SESSION=0;
	const MAGIC=15;
	public static function genSessionKey($isAuthorized=true,$isLong=true)
	{
		$firstByte=self::MAGIC+$sessionType+$sessionAuthorized;
		$secondByte=self::VERSION;
		$padding=rand(0,65535);// so random cho padding
		$time=time();//thoi gian hien tai
		$temp=pack('CCSL',$firstByte,$secondByte,$padding,$time);
		$crc=crc32($temp);
		$sessionType=$isLong?self::LONG_SESSION_TYPE:self::SHORT_SESSION_TYPE;
		$sessionAuthorized=$isAuthorized?self::AUTHORIZED_SESSION:self::UNAUTHORIZED_SESSION;;
		$result= pack('CCSLL',$firstByte,$secondByte,$padding,$crc,$time);
		$name=strtoupper(bin2hex($result));
		return $name;
	}
	public static function checkSessionKey($key)
	{
		//C = 1, C = 1, S = 2, L=4, L = 4
		if(strlen($key) != 24)
			return false;
		
		$key = self::hex2bin($key);
		$result= unpack('CfirstByte/CsecondByte/Spadding/Lcrc/Ltime',$key);
		$temp=pack('CCSL',$result['firstByte'],$result['secondByte'],$result['padding'],$result['time']);
		$inputCrc=crc32($temp);
		if ($result['crc'] <0)
		{
			  $result['crc'] += 4294967296;//for interger convert
		}
		if ($inputCrc <0)
		{
			  $inputCrc += 4294967296;//for interger convert
		}
		return $inputCrc==$result['crc'];
		//return true;

	}
	public static function hex2bin($str) 
	{
		$bin = "";
		$i = 0;
		do 
		{
			$bin .= chr(hexdec($str{$i}.$str{($i + 1)}));
			$i += 2;
		} while ($i < strlen($str));
		return $bin;
	}
}
?>